package com.library.controller;

import com.library.entity.BorrowRecord;
import com.library.entity.Reader;
import com.library.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/borrow")
public class BorrowController {

    @Autowired
    private BorrowService borrowService;

    @GetMapping("/myRecords")
    public String myBorrowRecords(HttpSession session, Model model) {
        Reader reader = (Reader) session.getAttribute("reader");
        if (reader == null) {
            return "redirect:/reader/login";
        }
        
        List<BorrowRecord> records = borrowService.getReaderBorrowRecords(reader.getId());
        model.addAttribute("records", records);
        return "borrow/myRecords";
    }

    @PostMapping("/borrow")
    @ResponseBody
    public String borrowBook(@RequestParam Integer bookId, HttpSession session) {
        Reader reader = (Reader) session.getAttribute("reader");
        if (reader == null) {
            return "请先登录";
        }
        
        boolean success = borrowService.borrowBook(reader.getId(), bookId);
        return success ? "借阅成功" : "借阅失败，可能原因：图书已借完或超出借阅上限";
    }

    @PostMapping("/return")
    @ResponseBody
    public String returnBook(@RequestParam Integer recordId) {
        boolean success = borrowService.returnBook(recordId);
        return success ? "还书成功" : "还书失败";
    }

    @PostMapping("/renew")
    @ResponseBody
    public String renewBook(@RequestParam Integer recordId) {
        boolean success = borrowService.renewBook(recordId);
        return success ? "续借成功" : "续借失败，可能原因：已达续借次数上限或已逾期";
    }

    @GetMapping("/admin/records")
    public String adminBorrowRecords(Model model) {
        List<BorrowRecord> records = borrowService.getAllBorrowRecords();
        model.addAttribute("records", records);
        return "admin/borrowRecords";
    }

    @GetMapping("/admin/overdue")
    public String overdueRecords(Model model) {
        List<BorrowRecord> overdueRecords = borrowService.getOverdueRecords();
        model.addAttribute("overdueRecords", overdueRecords);
        return "admin/overdueRecords";
    }

    @GetMapping("/admin/borrowing")
    public String borrowingRecords(Model model) {
        List<BorrowRecord> borrowingRecords = borrowService.getBorrowingRecords();
        model.addAttribute("borrowingRecords", borrowingRecords);
        return "admin/borrowingRecords";
    }
}